﻿using System;
using System.ComponentModel;
using System.IO;
using System.Threading;

namespace TddBarForPhone
{
    class BuildWatcher
    {
        private bool _lastBuildIsNotTested;

        public void Launch(string dllToTestFilePath)
        {
            FileSystemEventHandler handler = (se, evt) =>
                                                 {
                                                     lock (this)
                                                     {
                                                         _lastBuildIsNotTested = true;
                                                     }
                                                 };
            var dllToTestDirectory = Directory.GetParent(dllToTestFilePath);
            var watcher = new FileSystemWatcher(dllToTestDirectory.FullName, "*.dll")
            {
                IncludeSubdirectories = true,
            };
            watcher.Changed += handler;
            watcher.Created += handler;
            watcher.Deleted += handler;
            watcher.EnableRaisingEvents = true;
        }
        
        public void KeepUpdatingForEver(DoWorkEventHandler updateHandler)
        {
            var nunitBackgroundWorker = new BackgroundWorker();
            nunitBackgroundWorker.DoWork += updateHandler;
            while (true)
            {
                if (!nunitBackgroundWorker.IsBusy)
                {
                    lock (this)
                    {
                        if (_lastBuildIsNotTested)
                        {
                            _lastBuildIsNotTested = false;
                            nunitBackgroundWorker.RunWorkerAsync();
                        }
                    }
                }
                Thread.Sleep(TimeSpan.FromSeconds(1));
            }
        }
    }
}
